import GWVideoPlaybackCom from './videoPlaybackCom.vue';
export default {
    components: {
        GWVideoPlaybackCom
    },
    data() {
        return {
            timeInterval: null,

            // 顶部类型导航切换
            tabMainNumber: 1,
            tabTopNumber: 0,
            confirmedNo: false,
            confirmedOk: false,

            // 顶部类型分类数量
            topAllNumber: 0,
            topGzAllNumber: 0,
            topGgAllNumber: 0,
            topXxAllNumber: 0,
            topSzAllNumber: 0,
            topZcAllNumber: 0,

            // 中间头部数量
            contLeftAllNumber: 0,
            contLeftAllType: '全部快照',
            contTabAffirmNo: 0, // 待确认
            contTabAffirmOK: 0, // 已确认

            // 搜索框
            inputStyleMain: false,
            mainSearchCon: '',
            indexLeftBoxShow: null,

            allSnapshoot: [], // 所有快照记录-渲染页面

            // 弹出层信息
            popAdmin: '',
            popType: '', // 事件类型
            popTime: '', // 时间
            popIncident: '', // 事件名
            popConfirmremark: '', // 处理意见
            acknowledgingTime: '', // 已确认事件的确认时间
            timeId: '', // 事件id

            handlingSuggestion: '', // 处理意见--监听输入内容

            // 分页组件
            snapshootType: '全部', // 事件类型：全部、故障、警告、信息、设置、资产
            confirm: 0, // 0：全部、1:已确认、2：待确认
            total: '',
            pageSize: 25, // 每页条数
            pageNo: 1, // 页码

            // 保留原页码
            allListPageNo: 1,
            TBCListPageNo: 1,
            confirmedListPageNo: 1,

            // 加载loading
            loading: false,
            state: '',
            openSearch: false, // 判断是否处于搜索状态
            numberStrAll: '',
            tabTopList: [],

            // 确认快照时是否为误报
            radio1: null,
            kzTitle: '',
            attrCurrentList: null,
            wuBao: '',
            wuBaoShow: false,
            onAffirmShow: true,
            setIntervalOk: 0,
            typeList: [],
            tabId: -1,

            listType: [{
                check: false,
                title: '故障',
                tabTopId: 0,
                level: 0,
                value: 0,
                img: require('./Images/kuaizhao_guzhang.png')
            }, {
                check: false,
                title: '警告',
                tabTopId: 0,
                level: 0,
                value: 0,
                img: require('./Images/kuaizhao_jinggao.png')
            }, {
                check: false,
                title: '信息',
                tabTopId: 0,
                level: 0,
                value: 0,
                img: require('./Images/kuaizhao_xinxi.png')
            }, {
                check: false,
                title: '设置',
                tabTopId: 0,
                level: 0,
                value: 0,
                img: require('./Images/kuaizhao_shezhi.png')
            }, {
                check: false,
                title: '资产',
                tabTopId: 0,
                level: 0,
                value: 0,
                img: require('./Images/kuaizhao_zichan.png')
            }],
            activeNm: [],

            // 录像回放
            videoShow: false,
            videoValue: {},
            videoName: ''
        };
    },
    mounted() {
        let query = this.$route.query;
        const {
            id
        } = query;
        if (id) {
            this.tabId = parseInt(id, 10);
        }
        this.getRealTimeEventTypeConfig();

    },
    methods: {

        // 组件关闭录像回放窗口
        onBtnClose() {
            this.videoShow = false;
        },

        // 查找录像回放列表
        getPlayback(token, start, end) {
            this.videoShow = true;
            let docData = [];
            if (!window.localStorage.ac_session) {
                this.myUtils.messageType('warning', '流媒体服务连接失败！');
                return;
            }
            this.$api
                .getVideoSearch({
                    hostUrl: '/api/v1/Search',
                    session: window.localStorage.ac_session,
                    token,
                    type: 'record', // 类型为视频回放
                    start,
                    end
                })
                .then(res => {
                    let result = JSON.parse(res.data.data);
                    if (!result.record) {
                        this.myUtils.messageType('warning', '该时间没有对应录像回放记录！');
                        return;
                    }
                    let list = result.record;
                    if (!list) {
                        this.myUtils.messageType('warning', '该时间没有对应录像回放记录！');
                        return;
                    }
                    if (list.length > 0) {
                        list.forEach((item, i) => {
                            let obj = {};
                            let strPathTo = [];
                            if (this.searchType === 'record') {
                                obj.info =
                                    this.timeFormat(item.strStartTime) +
                                    ' - ' +
                                    this.timeFormat(item.strEndTime);
                            } else {
                                obj.info = this.timeFormat(item.strEndTime);
                            }

                            strPathTo = item.strPath.split('/');
                            item.strPathTo = strPathTo[strPathTo.length - 1];
                            item.downUrl = this.$store.state.serverUrl + item.strPath;
                            item.active = '';
                            obj.data = item;
                            docData.push(obj);
                        });
                    }
                    this.videoValue = docData[0];
                })
                .catch(err => {
                    console.log(' 查找回放记录失败！', err);
                    this.myUtils.messageType('warning', '查找回放记录失败！');
                });
        },

        onVideo(item) {
            if (!window.localStorage.ac_session) {

                // h5流媒体视频
                this.myUtils.streamLogin();
            }

            this.videoName = '';
            if (item.relatedVideo === '') {
                this.$message.warning('当前快照没有录像回放！');
                return;
            }
            let date = new Date(item.time).getTime() / 1000;

            let dateS = this.myUtils.getTimeStampToTime((date - 300) * 1000); // 前五分钟
            let dateE = this.myUtils.getTimeStampToTime((date + 300) * 1000); // 后五分钟

            this.$api.getEquipNumCatVideoId(String(item.relatedVideo)).then((res) => {
                if (res.data.code === 200) {
                    if (res.data.data) {
                        let videoObj = res.data.data[0];
                        this.videoName = videoObj.path.slice(3);
                        this.getPlayback(videoObj.channelNum, dateS, dateE);
                    } else {
                        this.$message.warning('当前快照没有录像回放！');
                    }
                } else {
                    this.$message.warning('当前快照没有录像回放！');
                }
            });
        },

        // 关闭视频回放
        onCloseVideo() {
            this.videoShow = false;
        },

        // 后五分钟
        addThreeS(dateStr) { // dateStr格式为yyyy-mm-dd hh:mm:ss
            let dt = new Date(dateStr.replace(/-/, '/')); // 将传入的日期格式的字符串转换为date对象 兼容ie
            // var dt=new Date(dateStr);//将传入的日期格式的字符串转换为date对象 非ie
            let ndt = new Date(dt.getTime() + 30000000); // 将转换之后的时间减去两秒
            let result = {
                year: parseInt(ndt.getFullYear()),
                month: parseInt(ndt.getMonth() + 1),
                day: parseInt(ndt.getDay()),
                hour: parseInt(ndt.getHours()),
                minute: parseInt(ndt.getMinutes()),
                second: parseInt(ndt.getSeconds())
            }
            return result;
        },

        // 前五分钟
        reduceTwoS(dateStr) { // dateStr格式为yyyy-mm-dd hh:mm:ss
            let dt = new Date(dateStr.replace(/-/, '/')); // 将传入的日期格式的字符串转换为date对象 兼容ie
            // var dt=new Date(dateStr);//将传入的日期格式的字符串转换为date对象 非ie
            let ndt = new Date(dt.getTime() - 30000000); // 将转换之后的时间减去两秒
            let result = {
                year: parseInt(ndt.getFullYear()),
                month: parseInt(ndt.getMonth() + 1),
                day: parseInt(ndt.getDay()),
                hour: parseInt(ndt.getHours()),
                minute: parseInt(ndt.getMinutes()),
                second: parseInt(ndt.getSeconds())
            }
            return result;
        },

        radioVla(no) {
            console.log('no-', no);
        },

        // 获取实时快照类别配置
        getRealTimeEventTypeConfig() {
            if (this.timeInterval) {
                clearInterval(this.timeInterval);
            }
            this.$api
                .getRealTimeEventTypeConfig()
                .then((rt) => {
                    if (rt.data.code === 200) {
                        let typeList = rt.data.data;
                        let levelList = [];
                        this.tabTopList = [];
                        let numberStrAll = '';
                        for (let i = 0; i < typeList.length; i++) {
                            let btnValue = [];
                            for (
                                let j = typeList[i].snapshotLevelMin; j <= typeList[i].snapshotLevelMax; j++
                            ) {
                                btnValue += j + ',';
                            }
                            levelList += btnValue.substring(0, btnValue.length - 1) + ';';
                            numberStrAll += btnValue.substring(0, btnValue.length - 1) + ';';

                            typeList[i].level = btnValue.substring(0, btnValue.length - 1);

                            // 整理快照类型
                            this.listType.forEach(itemJ => {
                                if (typeList[i].snapshotName === itemJ.title) {
                                    let obj = {
                                        title: itemJ.title,
                                        img: itemJ.img,
                                        level: typeList[i].level,
                                        value: 0,
                                        check: true
                                    }

                                    this.tabTopList.push(obj);
                                    this.activeNm.push(typeList[i].snapshotName)

                                }
                            })

                        }
                        this.numberStrAll = numberStrAll.substr(0, numberStrAll.length - 1);

                        // 页面初始化默认选中第一个类型
                        this.eventTypeList = levelList.toString().replace(/;/g, ',');

                        this.typeList = typeList;

                        this.getRealTimeEventCount();
                        this.timeInterval = setInterval(() => {
                            this.getRealTimeEventCount();
                        }, 5000)
                    } else {
                        this.$message.error(rt.data.message);
                        this.loading = false;
                    }
                })
                .catch((err) => {
                    this.loading = false;
                    console.log('err---', err);
                });
        },

        // 获取实时快照事件总数---支持动态配置实时快照项
        getRealTimeEventCount() {
            this.loading = true;
            this.$api
                .getRealTimeEventCount(this.numberStrAll)
                .then((rt) => {
                    if (rt.data.code === 200) {
                        let rtList = rt.data.data;
                        if (rtList.length > 0) {
                            rtList.forEach((item, i) => {
                                this.tabTopList.forEach(itemJ => {
                                    if (item.name === itemJ.title) {
                                        itemJ.value = item.value;
                                    }
                                })
                            });
                        }

                        if (this.tabId !== -1) {
                            this.onTabTop(this.tabId, this.tabTopList[this.tabId]);
                        }
                        this.getRealTimeEvent();
                    } else {
                        this.$message.error(rt.data.message);
                    }

                    this.loading = false;
                })
                .catch((err) => {
                    this.loading = false;
                    console.log('err---', err);
                });
        },

        // 获取当前系统报警实时事件--数据列表
        getRealTimeEvent() {
            this.loading = true;
            let data = {
                pageNo: this.pageNo,
                pageSize: this.pageSize,
                eventType: this.eventTypeList,
                eventName: this.state
            };
            this.$api
                .getRealTimeEvent(data)
                .then((rt) => {
                    if (rt.data.code === 200) {
                        let allSnapshoot = rt.data.data.list;
                        this.total = rt.data.data.totalCount;
                        if (allSnapshoot.length > 0) {
                            allSnapshoot.forEach((item, i) => {
                                item.guid = item.guid;
                                item.time = item.time.replace(/T/, ' ');
                                item.typeIcon = this.judgeSnapshotType(item.level).typeIcon;
                                item.typeSz = this.judgeSnapshotType(item.level).typeSz;
                                if (item.relatedVideo) {
                                    item.relatedVideoState = true;
                                } else {
                                    item.relatedVideoState = false;
                                }
                                item.spanTextColor = this.judgeSnapshotType(
                                    item.level
                                ).spanTextColor;
                            });
                        }
                        this.allSnapshoot = allSnapshoot;
                    } else {
                        this.$message.error(rt.data.message);
                        this.loading = false;
                    }

                    this.loading = false;
                })
                .catch((err) => {
                    this.loading = false;
                    console.log('err---', err);
                });
        },

        // 判断快照类型
        judgeSnapshotType(no) {
            let type = {
                typeIcon: '',
                spanTextColor: '',
                typeSz: ''
            };
            if (no >= 10003 && no <= 10005) {
                type = {
                    typeIcon: require('./Images/kuaizhao_guzhang.png'),
                    spanTextColor: 'spanTextColor_gz',
                    typeSz: '故障'
                };
            } else if (no === 0 || no === 1) {
                type = {
                    typeIcon: require('./Images/kuaizhao_xinxi.png'),
                    spanTextColor: 'spanTextColor_xx',
                    typeSz: '信息'
                };
            } else if (no === 10001) {
                type = {
                    typeIcon: require('./Images/kuaizhao_shezhi.png'),
                    spanTextColor: 'spanTextColor_sz',
                    typeSz: '设置'
                };
            } else if (no === 10002) {
                type = {
                    typeIcon: require('./Images/kuaizhao_zichan.png'),
                    spanTextColor: 'spanTextColor_zc',
                    typeSz: '资产'
                };
            } else if (no > 1 && no < 10) {
                type = {
                    typeIcon: require('./Images/kuaizhao_jinggao.png'),
                    spanTextColor: 'spanTextColor_jg',
                    typeSz: '警告'
                };
            }
            return type;
        },

        // 快照确认事件
        onAffirm() {
            let wuBao = 0;
            let attrCurrentList = this.attrCurrentList;

            if (this.wuBaoShow) {
                if (this.radio1 != 0 && this.radio1 != 1) {
                    this.$message.warning('请确认是否为误报!');
                    return;
                }
            }
            if (Number(this.radio1)) {
                wuBao = 1;
            }
            let guid = attrCurrentList.guid;
            let data = {
                GUID: guid,
                eventMsg: this.popIncident,
                time: this.popTime,
                procMsg: this.handlingSuggestion,
                userName: sessionStorage.getItem('userName'),
                wuBao: wuBao
            };
            this.onAffirmShow = false;
            this.$api
                .getConfirmedRealTimeEvent(data)
                .then((rt) => {
                    if (rt.data.code === 200) {
                        this.$message({
                            message: '确认成功!',
                            type: 'success'
                        });
                        this.onAffirmShow = true;
                        this.confirmedNo = false;
                        this.confirmedOk = false;
                        this.handlingSuggestion = '';
                        this.getRealTimeEventCount(this.snapshootType, this.confirm);
                    } else {
                        this.onAffirmShow = true;
                        this.$message.error(rt.data.message);
                        this.confirmedNo = false;
                        this.confirmedOk = false;
                        this.handlingSuggestion = '';
                    }
                })
                .catch((err) => {
                    console.log('err---', err);
                });
        },

        // 打开事件快照-事件详情
        onTBC(item, type) {
            this.confirmedNo = true;
            this.radio1 = null;
            this.wuBaoShow = false;
            this.attrCurrentList = item;
            if (item.ycyxno > 0 && item.type != null) {
                this.wuBaoShow = true;
            }
            if (item.bConfirmed) {
                this.confirmedOk = true;
                this.acknowledgingTime = item.dtConfirm.slice(0, 19).replace(/T/, ' ');
            } else {
                this.confirmedNo = true;
            }
            this.popAdmin = item.userConfirm; // 确认人
            this.popType = item.typeSz + '详情';
            this.popTime = item.time;
            this.popIncident = item.eventMsg;
            this.popConfirmremark = item.procAdviceMsg;
        },

        // 关闭事件快照-遮罩层
        closeEquipDialog() {
            this.confirmedNo = false;
            this.confirmedOk = false;
            this.handlingSuggestion = '';
        },

        // 判断tab高亮
        tabActive(level, data) {

            // 最少保留一个类型
            if (this.activeNm.length === 1 && (data.title === this.activeNm[0])) {
                return;
            }

            // 传过来点击的类型level
            let eventTypeList = '';
            this.activeNm = [];
            this.tabTopList.forEach(item => {
                if (item.level === level) {
                    item.check = !item.check;
                }
                if (item.check) {
                    eventTypeList += item.level + ',';
                    this.activeNm.push(item.title);
                }
            })
            this.eventTypeList = eventTypeList.substr(0, eventTypeList.length - 1);
        },

        // 顶部tab切换
        onTabTop(no, item) {
            this.tabActive(item.level, item);

            // 重复点击最后一个禁止请求
            if (this.activeNm.length === 1 && (item.title === this.activeNm[0])) {
                return;
            }

            this.setIntervalOk = 1;
            this.pageNo = 1;
            this.tabTopNumber = no;
            if (this.total >= 1) {
                this.$refs.pagination.internalCurrentPage = 1;
            }
            this.getRealTimeEvent();
        },

        // 中间内容tabNab切换
        onTabMain(no) {
            this.tabMainNumber = no;
            this.pageNo = 1;
            this.state = '';
            this.openSearch = false;

            // 返回原页码
            if (no === 1) {

                // 全部列表-页码
                this.confirm = 0;
                if (this.allSnapshoot != '') {
                    this.$refs.pagination.internalCurrentPage = this.allListPageNo;
                }
                this.getRealTimeEventCount(this.snapshootType, 0);
            } else if (no === 2) {
                this.confirm = 2;
                if (this.allSnapshoot != '') {

                    // 待确认列表-页码
                    this.$refs.pagination.internalCurrentPage = this.TBCListPageNo;
                }
                this.getRealTimeEventCount(this.snapshootType, 2);
            } else {
                this.confirm = 1;
                if (this.allSnapshoot != '') {

                    // 待确认列表-页码
                    this.$refs.pagination.internalCurrentPage = this.confirmedListPageNo;
                }

                // 已确认列表-页码
                this.getRealTimeEventCount(this.snapshootType, 1);
            }
        },

        // 页码大小改变时触发事件-每页条数
        handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.pageNo = 1;

            // 改变每页条数后将从第一页查起
            this.allListPageNo = 1;
            this.TBCListPageNo = 1;
            this.confirmedListPageNo = 1;
            this.$refs.pagination.internalCurrentPage = 1;
            this.getRealTimeEvent();
        },

        // 页码改变事件
        handleCurrentChange(currentPage) {
            this.pageNo = currentPage;
            this.getRealTimeEvent();
        }
    },
    beforeRouteUpdate() {
        if (this.timeInterval) {
            clearInterval(this.timeInterval);
        }
    },
    beforeDestroy() {
        if (this.timeInterval) {
            clearInterval(this.timeInterval);
        }
        this.onBtnClose();
    },

    destroyed() {
        if (this.timeInterval) {
            clearInterval(this.timeInterval);
        }
        this.onBtnClose();
    }
};